package cn.qiao.zk.order;

import lombok.Data;
import org.apache.zookeeper.ZooKeeper;

import java.util.LinkedList;
import java.util.List;
import java.util.Random;

/**
 * desc:
 *
 * @author qiao
 * @date 2023年05月05日 21:21
 */
@Data
public class ZookListener {

    private static final String SERVER_PATH="/product";

    private static final String ZK_ADDRESS="127.0.0.1:2181";

    private static final int ZK_TIMEOUT = 20000;

    private ZooKeeper zooKeeper;

    private List<String> paths = new LinkedList<>();

    public void init(){
        try{
            zooKeeper = new ZooKeeper(ZK_ADDRESS,ZK_TIMEOUT,(WatchEvent)->{
                getChilds();
            });
        }catch (Exception e){
            e.printStackTrace();
        }
    }

    private void getChilds(){
        List<String> ips = new LinkedList<>();
        try{
            //添加监听
            List<String> childs = this.zooKeeper.getChildren(SERVER_PATH,true);
            for(String child:childs){
                byte[] obj = zooKeeper.getData(SERVER_PATH+"/"+child,false,null);
                String path = new String(obj,"utf-8");
                ips.add(path);
            }
            this.paths = ips;
        }catch (Exception e){
            e.printStackTrace();
        }
    }

    public String getPath(){
        if(paths.isEmpty()){
            return null;
        }
        int index = new Random().nextInt(paths.size());
        return paths.get(index);
    }
}
